package com.ssu.judea.travlog.model;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.log4j.Logger;
import org.json.JSONObject;

import statics.TravlogVars;
import twitter4j.TwitterException;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.oreilly.servlet.MultipartRequest;
import com.ssu.judea.travlog.controller.WebServlet;
import com.ssu.judea.travlog.vo.Attach;
import com.ssu.judea.travlog.vo.Content;
import com.ssu.judea.travlog.vo.DatePost;
import com.ssu.judea.travlog.vo.Member;
import com.ssu.judea.travlog.vo.Post;
import com.ssu.judea.travlog.vo.Result;
import com.ssu.judea.travlog.vo.ResultRecentPost;

import comm.util.SqlMapLoader;
import comm.util.Thumbnail;
import comm.util.TravlogFileRenamePolicy;
import comm.util.TravlogHashMap;
import comm.util.TwitterAPI;

public class TravlogDAO {
	public Logger logger = Logger.getLogger(TravlogDAO.class);
	
	public SqlMapClient sqlMapper = SqlMapLoader.getInstance();
	
	public TwitterAPI twit;
	
	public Member authorize(HttpServletRequest request, HttpServletResponse response) throws ParserConfigurationException, IOException, SQLException{
		if(twit==null)twit = new TwitterAPI();
		return twit.regMember(request, response);
	}
	
	public Member authorizeFromMobile(HttpServletRequest request, HttpServletResponse response) throws ParserConfigurationException, IOException, SQLException{
		if(twit==null)twit = new TwitterAPI();
		return twit.regMemberFromMobile(request, response);
		
	}
	
	public Member getMemberBySession(String session){
		Member mem = null;
		try {
			mem = (Member) sqlMapper.queryForObject("member.getMemberBySession",session);
		} catch (SQLException e) {
			return null;
		}
		return mem;
	}
	
	public Member getMemberBySeq(String seq){
		Member mem = null;
		try {
			mem = (Member) sqlMapper.queryForObject("member.getMemberBySeq",seq);
		} catch (SQLException e) {
			return null;
		}
		return mem;
	}
	public Member getMemberById(String id){
		Member mem = null;
		try {
			mem = (Member) sqlMapper.queryForObject("member.getMemberById",id);
		} catch (SQLException e) {
			return null;
		}
		return mem;
	}
	
	public Member getMemberByNumber(String num){
		Member mem = null;
		try {
			if(sqlMapper==null)sqlMapper = SqlMapLoader.getInstance();
			mem = (Member) sqlMapper.queryForObject("member.getMemberByNumber",num);
		} catch (SQLException e) {
			return null;
		}
		return mem;
	}
	
	public void getMyTravlogList(){
		
	}
	
	/*
	 * jpg,gif,png 확장자로 이미지 검출
	 * @return : TravlogHashMap (업로드된 파라미터들 정보)
	 */
	public TravlogHashMap fileUpload(HttpServletRequest request) throws UnsupportedEncodingException{
        String uploadedFileName = "";
        String dataSeq = "";
        String articleSeq = "";
        TravlogHashMap hm = new TravlogHashMap();
        String savePath = request.getSession().getServletContext().getRealPath(TravlogVars.IMG_UPLOAD_PATH);
        File f = new File(savePath);
        f.mkdir();
        
        int sizeLimit = 5 * 1024 * 1024 ; // 5메가까지 제한 넘어서면 예외발생
        TravlogFileRenamePolicy renamePolicy = new TravlogFileRenamePolicy();
                MultipartRequest multi = null;
				try {
					multi = new MultipartRequest(request, savePath, sizeLimit,"UTF-8", renamePolicy );
				} catch (IOException e) {
					uploadedFileName = "FAIL";
				}
                Enumeration formFileNames=multi.getFileNames();  // 파일폼의 이름 반환
                Enumeration formNames = multi.getParameterNames(); // 폼의 이름 반환
                
                String formFileName = (String)formFileNames.nextElement(); // 자료가 많을 경우엔 while 문을 사용
                String fileName = multi.getFilesystemName(formFileName); // 파일의 이름 얻기
                String formName = null;
                while(formNames.hasMoreElements()){
                                formName = (String) formNames.nextElement();
                                
                                hm.put(formName.toUpperCase(), multi.getParameter(formName).toString());
                }

            if(fileName == null) { // 파일이 업로드 되지 않았을때
            	uploadedFileName = "FAIL";
            } else { // 파일이 업로드 되었을때
                int dot = fileName.lastIndexOf(".");
                String ext = "";
                    if (dot != -1) {
                        ext = fileName.substring(dot+1);  // without "."
                        ext = ext.toLowerCase();
                    }
                    hm.put("ORIGIN_FILE", renamePolicy.originName);
                    File f2 = new File(savePath+"/"+fileName);
                    String mimeType = new MimetypesFileTypeMap().getContentType(f2);
                    
                    if(ext.equals("png")||ext.equals("jpg")||ext.equals("jpeg")||ext.equals("gif")){
                    	uploadedFileName=new String(fileName);
                    	
                    	/*
                    	if(mimeType.indexOf("image")==-1){
                    		uploadedFileName="NOT_IMAGE";
                    		f2.delete();
                    	}else{
                    		//Success
                    	}*/
                    }else{
                    	uploadedFileName="NOT_IMAGE";
                    	f2.delete();
                    }
                
            } // end if
            logger.debug("UploadedFileName: "+uploadedFileName);
            String origin = savePath+"/"+uploadedFileName;
            Thumbnail thumb = new Thumbnail();
            thumb.createThumbnail(origin, origin.substring(0, origin.lastIndexOf("."))+"_s"+origin.substring(origin.lastIndexOf(".")), 50);
            
            //최종적으로 업로드 된 파일 저장
            hm.put("UPLOAD_FILE", uploadedFileName);
        return hm;
    }
	
	
	public ArrayList<Member> getFollowersInfo(String curClientSeq) {
		ArrayList<Member> list = null;
		
		if(sqlMapper==null)sqlMapper = SqlMapLoader.getInstance();
		
		Member mem = getMemberBySeq(curClientSeq);
		
		String passkey = mem.getTwitterpasskey();
		
		//트윗 follow 처리
		if(twit==null)twit = new TwitterAPI();
		ArrayList<Integer> followersIds = null;
		if(passkey.length()>0)
			followersIds = twit.getMyFollowersList(passkey);
		
		if(followersIds!=null && followersIds.size()>0){
			list = new ArrayList<Member>();
			for(int i = 0; i<followersIds.size();i++){
				Member currentItem = getMemberByNumber(followersIds.get(i).toString());
				
				if(currentItem!=null)list.add(currentItem);
			}
			
			logger.debug("getFollowersInfo Result"+list.size());
		}
		return list;
	}
	
	public String doFollow(String targetId,String memberseq){
		String passkey = getMemberBySeq(memberseq).getTwitterpasskey();
		String result = TravlogVars.FAIL;
		
		//트윗 follow 처리
		if(twit==null)twit = new TwitterAPI();
		
		if(passkey.length()>0)
			result = twit.follow(passkey, targetId);
		
		logger.debug("Twitter Follow 결과"+result);
		
		return result;
	}
	
	public String doWriteMention(String text,String memberseq){
		String passkey = getMemberBySeq(memberseq).getTwitterpasskey();
		logger.debug("=====doWrite in AndroidDAO 넘어온 내용");
		logger.debug(text);
		String result = TravlogVars.FAIL;
		
		//트윗 포스팅 처리
		if(twit==null)twit = new TwitterAPI();
		
		if(passkey.length()>0)
			result = twit.writeTwit(passkey, text);
		
		logger.debug("Twitter포스팅 결과"+result);
		
		return result;
	}
	
	public ArrayList<DatePost> getUserPostDateListArrayList(String memberseq) {
		ArrayList<DatePost> resultList = null;
		try {
			resultList = (ArrayList<DatePost>)sqlMapper.queryForList("post.getUserPostDateList", memberseq);
		} catch (SQLException e) {
			return null;
		}
		return resultList;
	}
	
}
